package com.loong.web.gp4j.component.mail;

import java.util.concurrent.ExecutorService;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.loong.tool.lang.Strings;
import com.loong.web.gp4j.service.error.ErrorService;

/**
 * 邮件组件
 *
 * @author 张成轩
 */
@Component
public class MailComponent {

	@Resource
	private JavaMailSender mailSender;
	@Resource
	private ErrorService errorService;
	@Resource(name = "mailThreadPool")
	private ExecutorService threadPool;
	@Value("${mail.from}")
	private String from;
	@Value("${web.encoding}")
	private String encoding;

	/**
	 * 发送邮件
	 * 
	 * @param subject 标题
	 * @param html 内容
	 * @param to 收件人
	 */
	public void send(String subject, String html, String to) {

		send(subject, html, to, null);
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject 标题
	 * @param html 内容
	 * @param to 收件人
	 * @param cc 抄送人
	 */
	public void send(String subject, String html, String to, String cc) {

		send(subject, html, to, cc, null);
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject 标题
	 * @param html 内容
	 * @param to 收件人
	 * @param cc 抄送人
	 * @param bcc 暗送人
	 */
	public void send(String subject, String html, String to, String cc, String bcc) {

		threadPool.execute(new Runnable() {

			@Override
			public void run() {

				try {
					send();
				} catch (MessagingException | RuntimeException e) {
					errorService.error(e);
				}
			}

			private void send() throws MessagingException, MailException {

				MimeMessage message = mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(message, true, encoding);
				helper.setFrom(from);
				helper.setTo(to.split(";"));
				if (Strings.isNotNull(cc))
					helper.setCc(cc.split(";"));
				if (Strings.isNotNull(bcc))
					helper.setBcc(bcc.split(";"));
				helper.setSubject(subject);
				helper.setText(html, true);
				mailSender.send(message);
			}
		});
	}
}
